package com.central.apps.handler.contract;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.common.feign.WorkflowClient;
import com.central.app.entity.TBFile;
import com.central.app.service.CheckConNodeService;
import com.central.app.service.HandlerService;
import com.central.apps.common.util.DateUtiles;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.util.SysUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2022/9/27.
 */
@Slf4j
@Component
public class ConstopHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FileSynUtilService fileSynUtilService;
    @Resource
    private CheckConNodeService checkConNodeService;
    @Resource
    private ConchangeHandler conchangeHandler;
    @Autowired
    private WorkflowClient workflowClient;
    @Autowired
    private ConreviewHandler conreviewHandler;

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        //填充会签人员
        if ("submit".equals(flowNode.getId())) {
            List<Map<String, Object>> list3 = handlerService.findBySql("select isonline from gq_constop where id = " + id);
            //String conid = (String) list3.get(0).get("conid");
            if ("是".equals(list3.get(0).get("isonline"))) {
                //如果是线上评审，需要判断是否添加评审人员
                boolean res = conreviewHandler.isSetPersons(app, id);
                if (!res) {
                    return "选择线上评审后，需要添加评审组成员信息再提交审批";
                }
                //如果是线上评审，需要增加评审人员到会签表
                conreviewHandler.setcountersigns(app, id, app);
            }
        }
        //会签审批通过后，把会签意见同步到意见历史中
        if ("countersign".equals(flowNode.getId())) {
            boolean res = conreviewHandler.isOpinion(app, id);
            if (!res) {
                return "请填写审批意见再提交";
            }
            //提交会见意见后，置空主表评审意见
            conreviewHandler.setnullrevcomments(id,"gq_constop");
            //conreviewHandler.setRevcoments(app, id);
        }
        return super.beforeExcuteFlow(app, id, flowNode, op);
    }

    @Override
    public void afterMoveNode(String app, Long id) throws Exception {
        //驳回后同步评审意见到历史评审意见
        conreviewHandler.setAllRevcoments(app, id);
    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {

        //----------------------流程审批后代码逻辑-------------------------------------
        //合同终止
        if (flowNode.getId().equals("approval")) {
            //审核通过后增加库存
            boolean flag = op.isFlag();//判断是否审核通过
            if (flag) {
                //查询接收入库主表gq_concollandpay
                List<Map<String, Object>> list = handlerService.findBySql("select * from gq_constop where id=" + id);
                if (CollectionUtils.isNotEmpty(list)) {
                    //将上传的文件，添加到合同台账里边
                    String concode = (String) list.get(0).get("concode");
                    fileSynUtilService.insertFiles(app, id, concode);
                    try {
                        conchangeHandler.updateStatus(concode, "合同终止");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    //流程归档
                    fileSynUtilService.processarc(app, id + "", "合同终止", (String) list.get(0).get("concode"), (String) list.get(0).get("conname"));
                }
            }
        }
        //合同关闭
        if (flowNode.getId().equals("approvaltwo")) {
            //审核通过后增加库存
            boolean flag = op.isFlag();//判断是否审核通过
            if (flag) {
                //查询接收入库主表gq_concollandpay
                List<Map<String, Object>> list = handlerService.findBySql("select * from gq_constop where id=" + id);
                String concode = (String) list.get(0).get("concode");
                if (CollectionUtils.isNotEmpty(list)) {
                    //将上传的文件，添加到合同台账里边
                    fileSynUtilService.insertFiles(app, id, concode);
                    //将合同状态更改为关闭
                    String closttime = DateUtiles.getYmdhms(new Date());
                    String sql = "update gq_conaccount set constatus ='合同关闭' , closttime = '" + closttime + "' where concode = '" + concode + "'";
                    handlerService.updateBySql(sql);
//                    String sql2 = "update gq_coninfo set constatus ='合同关闭'  where concode = '" + concode + "'";
//                    handlerService.updateBySql(sql2);
                    try {
                        conchangeHandler.updateStatus(concode, "合同关闭");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                //合同终止关闭后，相对应的合同变更，合同履行，合同收付款，如果有审批流程，都应该关闭
                //根据合同编号查询  合同变更，合同节点完成检查，合同收付款，获取各个菜单的id值，查询未走完的流程数据，进行关闭。

                String sql = "select proc_ins_id from biz_flow_app where biz_num ='" + concode + " ' and status = 0";
                List<Map<String, Object>> lists = handlerService.findBySql(sql);
                if (CollectionUtils.isNotEmpty(lists)) {
                    for (Map<String, Object> stringObjectMap : lists) {
                        String procInsId = (String) stringObjectMap.get("proc_ins_id");
                        workflowClient.moveToEnd(procInsId);
                    }

                }

            }
        }
    }

    //合同终止，要把合同台账中的合同文档带到终止的合同文档下边， 审批通过后，不需要把合同终止的文档同步到合同台账，过程资料和财务资料是需要的
    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {

        if ("gq_constop".equals(objName)) {

            Long id = MapUtil.getLong(data, "id");
            // 查询合同台账，获取合同台账表中主键id，通过id查询合同文档集合，然后插入到合同终止里的合同文档，只读
            String concode = MapUtil.getStr(data, "concode");
            String sql = "select * from gq_conaccount where concode= '" + concode + "'";
            List<Map<String, Object>> list = handlerService.findBySql(sql);
            if (CollectionUtils.isNotEmpty(list)) {
                List<TBFile> tbFiles = checkConNodeService.selectFiles("conaccountApp", MapUtils.getLong(list.get(0), "id"));

                String del = "delete from tb_file where appname = 'only" + app + "' and recordid = '" + id + "'";
                handlerService.updateBySql(del);
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(tbFiles)) {
                    for (TBFile tbFile : tbFiles) {
                        //插入到合同终止
                        tbFile.setFileid(null);
                        tbFile.setAppname("only" + app);
                        tbFile.setRecordid(id);
                        checkConNodeService.insertConfiles(tbFile);
                    }
                }
            }
            //将主表中的评审意见添加到对应的子表评审意见位置。
            conreviewHandler.moverevcomments(data);

        }
    }
}
